#include "Main.h"

VOID Log(CHAR* szFormat, ...)
{
	CHAR szString[8192] = {NULL};
	va_list vaArgs;

	va_start(vaArgs, szFormat);
	vsprintf(szString, szFormat, vaArgs);
	va_end(vaArgs);

	time_t tTime;
	time(&tTime);
	CHAR szTime[128] = "";
	strftime(szTime, sizeof(szTime), "[%b/%d/%Y - %H:%M:%S]",localtime(&tTime));

	CHAR szLogPath[MAX_PATH] = {NULL};
	strcpy(szLogPath, Vars.szPath);
	strcat(szLogPath,"\\w3jsp.log");

	FILE* pLog = fopen(szLogPath, "a+");
	fprintf(pLog, "%s %s\n", szTime, szString);
	fclose(pLog);
}


INT StringTokenize(CHAR * input, CHAR separator, CHAR ** tokenbuf, INT maxtokens)
{
	CHAR * p = _strdup(input);
	INT i = 0;
	do {
		tokenbuf[i] = p;
		p = strchr(p, separator);
		if(p)
			*(p++) = 0;
	} while (p && ++i < maxtokens);
	delete[] p;
	return ++i;
}

__declspec(naked) DWORD GetCurrentTEB()
{
	__asm
	{
		mov eax,fs:[0x18]
		retn
	}
}

__declspec(naked) DWORD __fastcall SetCurrentTEB(DWORD dwValue)
{
	__asm
	{
		mov fs:[0x18], ecx
		retn
	}
}

typedef ULONG (__stdcall *pfnNtQueryInformationThread) (HANDLE, THREAD_INFORMATION_CLASS, PVOID, ULONG, PULONG);

TEB* GetTEBFromThread(HANDLE hThread)
{
	pfnNtQueryInformationThread NtQueryInformationThread = (pfnNtQueryInformationThread) GetProcAddress(LoadLibrary("ntdll.dll"), "NtQueryInformationThread");
    THREAD_BASIC_INFORMATION tbi;
    THREAD_INFORMATION_CLASS tic = ThreadBasicInformation;

	if (NtQueryInformationThread == NULL)
        return NULL;	

	if (NtQueryInformationThread(hThread, tic, &tbi, sizeof(tbi), NULL) == NULL)
		return (TEB*)tbi.TebBaseAddress;

	return NULL;
}